# -*- coding: utf-8 -*-
# @Date    : 2017-06-01 15:24:21
# @Author  : fancy (fancy@thecover.co)

from gevent import monkey; monkey.patch_all()
import time
import gevent
import urllib2
import threading

def urllib2_(url):
    try:
        urllib2.urlopen(url, timeout=10).read()
    except Exception as e:
        print e

def gevent_(urls):
    jobs = [gevent.spawn(urllib2_, url) for url in urls]
    gevent.joinall(jobs, timeout=10)
    for i in jobs:
        i.join()

def thread_(urls):
    a = []
    for url in urls:
        t = threading.Thread(target=urllib2_, args=(url, ))
        a.append(t)
    for t in a:
        t.start()
    count = 0
    for t in a:
        t.join()
        print count
        count += 1

if __name__ == '__main__':
    urls = ['http://www.bing.com'] * 50
    t1 = time.time()
    thread_(urls)
    t2 = time.time()
    print 'threading time: %s' % (t2 - t1)
    gevent_(urls)
    t3 = time.time()
    print 'gevent time: %s' % (t3 - t2)
    # for i in urls:
    #     urllib2_(i)
    # t4 = time.time()
    # print 'urllib time: %s' % (t4 - t3)
